package dodo.mindmap;

import geomerative.RPoint;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import processing.core.PApplet;

public class Link {
	
	Mindmap map;
	int id;
	Node from;
	Node to;
	float k;
	
	public Link(Mindmap map, Node from, Node to, float k){
		this.id = 0;
		this.map = map;
		this.from = from;
		this.to = to;
		this.k = k;
	}
	
	public Link(Mindmap map, int id, Node from, Node to, float k){
		this.id = id;
		this.map = map;
		this.from = from;
		this.to = to;
		this.k = k;
	}
	
	public Link(Mindmap map, int id){
		this.id = id;
		this.map = map;
		this.from = null;
		this.to = null;
		this.k = 0;
	}
	
	public Node getTo(Node n){
		if(from == n){
			return to;
		}else if(to == n){
			return from;
		}else {
			return null;
		}
	}
	
	public void draw(){
		RPoint direction = new RPoint(to.position);
		direction.sub(from.position);
		direction.normalize();
		
		direction.scale(from.getSize().x/2);
		direction.add(from.position);
		
		RPoint linefrom = new RPoint(direction);
		
		direction.sub(from.position);
		direction.normalize();
		direction.scale(-to.getSize().x/2);
		direction.add(to.position);
		
		map.parent.line(linefrom.x, linefrom.y, direction.x, direction.y);
	}
	
	public byte[] getMD5(){
		String input = "" + id + "" + k;
		
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");

			return md5.digest(input.getBytes());
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	public void updateFromXML(String xml){
		DOMParser parser = new DOMParser();
        try {
			parser.parse(new org.xml.sax.InputSource(new java.io.StringReader(xml)));
	        Document doc = parser.getDocument();
	        
	        org.w3c.dom.Node idea = doc.getElementsByTagName("object").item(0);
	        id = Integer.parseInt(idea.getAttributes().getNamedItem("pk").getNodeValue());
	        NodeList children = idea.getChildNodes();
	        for(int i=0; i < children.getLength(); i++){
	        	if(children.item(i).getAttributes().getNamedItem("name").getNodeValue() == "strength"){
	        		k = Float.valueOf(children.item(i).getNodeValue());
	        	}
	        }
	        
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void sendCreateLink(Link l){

		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost("http://172.16.1.5:80/ideavolution/link/new");
		String response;
		
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("from", String.valueOf(l.from.id)));
		params.add(new BasicNameValuePair("to", String.valueOf(l.to.id)));
		params.add(new BasicNameValuePair("strength", String.valueOf(l.k)));
		
		try {
			UrlEncodedFormEntity encoded_params = new UrlEncodedFormEntity(params);
			httppost.setEntity(encoded_params);
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			response = httpclient.execute(httppost, responseHandler);
			l.updateFromXML(response);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public String dbRequest(String field){
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(map.baseurl + "/ideavolution/link/" + id + "/" + field + "/");
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		try {
			return httpclient.execute(httppost, responseHandler);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public Node getDBFrom(){
		String pid = dbRequest("from_idea_id");
		if( pid != null ){
			int parent_id = Integer.parseInt(pid);
			if(map.nodes.containsKey(parent_id))
				return map.nodes.get(parent_id);
		}
		return null;
	}
	
	public Node getDBTo(){
		String pid = dbRequest("to_idea_id");
		if( pid != null ){
			int parent_id = Integer.parseInt(pid);
			if(map.nodes.containsKey(parent_id))
				return map.nodes.get(parent_id);
		}
		return null;
	}
	
	public float getDBStrength(){
		String pid = dbRequest("strength");
		return Float.parseFloat(pid);
	}
}
